package org.example.interceptors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.example.domain.beans.JwtParseInfo;
import org.example.utils.JwtUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 400 参数错误
 * 401 没有登录
 * 403  没有权限
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    private Log log = LogFactory.getLog(JwtTokenInterceptor.class);
    private JwtUtils jwtUtils;

    public JwtTokenInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return true;
        }
        log.info(String.format("请求地址：%s", request.getRequestURI()));
        String authorization = request.getHeader("Authorization");
        if(StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) {
            // 抽取出 access_token
            String access_token = authorization.replace("Bearer ", "");
            JwtParseInfo jpi = jwtUtils.validateAccessJwt(access_token);

            switch (jpi.getSignatureStatus()) {
                // 正常状态接着往下走
                case correct:
                    return true;
                // 签名过期了
                case expired:
                    // 自定义的状态
                    response.setStatus(567);
                    return false;
                case tamper:
                    response.setStatus(401);
                    return false;
            }
            return false;
        }else {
            response.setStatus(401);
            return false;
        }
    }
}
